﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Xml;
using System.Text;
using System.Web;
using System.Windows.Forms;
using SharePointClient;

namespace SharePointExplorer
{
    public partial class SharePointExplorer : Form
    {
        private List activelist = null;
        private Site site = null;
        private Connection connection=new Connection();

        public SharePointExplorer()
        {
            connection.Progress += new ProgressEventHandler(this.Progress);
            connection.OnFileoperation += new FileoperationHandler(connection_OnFileoperation);
            InitializeComponent();
        }

        void connection_OnFileoperation(object sender, FileoperationEventArgs e)
        {
            fileprogress.Minimum = 0;fileprogress.Maximum=e.Size ;
            fileprogress.Value = e.Loaded;
       
            fileprogress.ToolTipText = e.File.ToString();
        }
        public void Progress(object sender, ProgressEventArgs e)
        {
            activeOperation.Text = e.Operation;
            statusStrip1.Update();
        }
        private void EnterSharePoint(object sender, EventArgs e)
        {
            FillTree();
            
        }
        private void FillTree()
        {
            treeView.Nodes.Clear();
            do
            {

                try
                {
                    site = connection.Open(new Uri(tAddress.Text));
                    site.Load();
                }
                catch (UriFormatException uex)
                {
                    MessageBox.Show(uex.Message);
                    return;
                }
                catch (Exception ex)
                {

                    Login login = new Login();
                    login.Info = ex.Message;
                    if (login.ShowDialog() == DialogResult.Cancel) return;
                    site.Login("NTLM", login.Username, login.Password, login.Domain);
                    continue;


                }
            } while (site.NeedRefresh);
            FillTree(site);
        }
        void FillTree(Site site)
        {
            site.Refresh();
            treeView.Nodes.Clear();
            //TreeNode root = treeView.Nodes.Add(site.WebID.ToString(), site.Title);
            TreeNode root = treeView.Nodes.Add( site.Title);
            root.ToolTipText = site.Description;
            root.Tag=site;
            root.Nodes.Add("...Loading");
            treeView.SelectedNode = root;
        }

       

        private void LoadLists(object sender, TreeViewEventArgs e)
        {
            listView.Clear();
            listView.Columns.Add("Listenname").Width=listView.ClientRectangle.Width;
            Site site = (Site) e.Node.Tag;
            foreach (List list in site.Lists)
            {
                ListViewItem li = new ListViewItem();
                li.Name = list.Title;
                li.Text = list.Title;
                //li.ToolTipText = list.Description;
                li.Tag = list;
                listView.Items.Add(li);
               
            }
            
        }

        private void LoadTree(object sender, TreeViewEventArgs e)
        {
            Site site = (Site)e.Node.Tag;
            if (e.Node.Nodes.Count == 1 && e.Node.Nodes[0].Text == "...Loading")
            {
                e.Node.Nodes.Clear();

                foreach (Site sub in site.Sites)
                {
                    TreeNode rsub = e.Node.Nodes.Add( sub.Title);
                    //rsub.ToolTipText = sub.Description;
                    rsub.Tag = sub;
                    rsub.Nodes.Add("...Loading");
                }
            }

        }

        private void listView_ClientSizeChanged(object sender, EventArgs e)
        {
            listView.Columns[0].Width = listView.ClientRectangle.Width;
        }

        private void listView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView.SelectedItems.Count <= 0) return;
            List list =activelist= (List)listView.SelectedItems[0].Tag;
            UpdateView();
            
        }
        private void UpdateView()
        {
            List list=activelist;
            directory.Clear();
            if (list.Documents != null)
            {
                directory.Columns.Add("FileLeafRef", "Filename");
                directory.Columns.Add("ID", "ID");
                directory.Columns.Add("Created", "Erstellt am");
                directory.Columns.Add("Modified", "Geändert am");
                directory.SmallImageList = this.imageList1;
                

                foreach (Document doc in list.Documents)
                {
                    ListViewItem i = directory.Items.Add(doc.Filename);
                   
                    i.SubItems.Add(doc.ID.ToString());
                    i.SubItems.Add(doc.Created.ToString());
                    i.SubItems.Add(doc.Modified.ToString());
                    if (!imageList1.Images.ContainsKey(doc.Extension))
                    {
                        imageList1.Images.Add(doc.Extension, doc.GetIcon());
                    }
                    i.ImageKey = doc.Extension;
                }
                directory.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            }

            DataTable t = new DataTable();
            list.Fill(t, null);
            if (t.Equals(dataGridView.DataSource)) dataGridView.Refresh(); else            dataGridView.DataSource = t;
        }
        private void dataGridView_DragEnter(object sender, DragEventArgs e)
        {
            if (activelist!=null && activelist.Attributes["ServerTemplate"].Value=="101" && (e.AllowedEffect & DragDropEffects.Copy)== DragDropEffects.Copy) e.Effect= DragDropEffects.Copy;
            
        }

        private void dataGridView_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(System.Windows.Forms.DataFormats.FileDrop))
            {
                object file = e.Data.GetData(System.Windows.Forms.DataFormats.FileDrop);
                if (file is string[])
                {
                    string[] filenames = (string[]) file;
                    for (int i = 0; i < filenames.Length; i++)
                    {
                        object o=connection.Upload(filenames[i],activelist.RootFolderUri);
                    }
                }
                DataTable t = new DataTable();
                activelist.Fill(t, null);
                dataGridView.DataSource = t;
            
            }
        }

        private void directory_DragLeave(object sender, EventArgs e)
        {
            
        
        }

        private void directory_ItemDrag(object sender, ItemDragEventArgs e)
        {
           
            string [] files=new string[directory.SelectedItems.Count];
            int i = 0;
            foreach (ListViewItem item in directory.SelectedItems)
            {
                int id = Convert.ToInt32(item.SubItems[1].Text);
                string locfile = Environment.GetEnvironmentVariable("TEMP") + "\\" + activelist.Documents[id].Filename;
                if (activelist.Documents[id].Download(locfile))    files[i++] = locfile;
            }
            if (i > 0)
            {
                System.Windows.Forms.DataObject dataObject = new DataObject(DataFormats.FileDrop, files);
                DoDragDrop(dataObject, DragDropEffects.Copy | DragDropEffects.Move);
            }
        }

        private void directory_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] drops = (string[])e.Data.GetData(DataFormats.FileDrop);
                foreach (string drop in drops) connection.Upload(drop, activelist.RootFolderUri);
                activelist.Refresh();
                tRefresh_Click(this, new EventArgs());
                
            }
        }

        private void directory_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
        {
            System.Diagnostics.Debugger.Break();
        }

        private void directory_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy | DragDropEffects.Move;
        }

        private void tRefresh_Click(object sender, EventArgs e)
        {
            if (activelist != null) 
            {
                activelist.Refresh();
                UpdateView();
            }
            if (treeView.SelectedNode != null)
            {
                Site s = (Site)treeView.SelectedNode.Tag;
                s.Refresh();
            }
            if (site != null) FillTree(site);
            else FillTree();
        }

        private void tAddress_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter)
            {
                if (!tAddress.Items.Contains(tAddress.Text)) tAddress.Items.Add(tAddress.Text);
                tRefresh_Click(this, new EventArgs());
                e.Handled = true;
            }
            else e.Handled = false;
        }

        

    }

}
